<template>
    <!-- 头部 -->
    <Header title='JD商城 ~购物车内容'>
        <template #left>
            <van-icon name="arrow-left" @click="tobackFn" />
        </template>
    </Header>
    <!--商品内容  -->
    <div v-for="item in cartList" class="box" :key="item.proid">
        <p class="imgbox">
            <!-- 每一个按钮 -->
        <p> <van-radio @click="updateStatus(item.cartid, !item.flag)" :checked="item.flag" class="select-item" name="1"></van-radio>            
        </p>
        <p> <img :src="item.img1" alt=""></p>
        </p>
        <div class="rightBox">
            <p class="pronamebox">{{ item.proname }}</p>
            <p style="color:red">￥{{ item.originprice }}元</p>
            <p><van-stepper v-model="item.num" theme="round" button-size="22" disable-input /></p>
            <p style="float:right"><van-button color="linear-gradient(to right, #ff6034, #ee0a24)" size="mini"
                    type="success" @click="delFn(item.cartid)"> 删除</van-button></p>
        </div>

    </div>

    <!-- 商品推荐列表 -->
    <ul class="recommend">
        <li class="smlbox" v-for="item in recommendlist">
            <p><img :src="item.img1" alt=""></p>
            <h3>{{ item.brand }}</h3>
            <p>{{ item.proname }}</p>
            <p style="color:red">￥：{{ item.originprice }}元</p>
        </li>
    </ul>

    <!-- 底部 -->
    <van-submit-bar class="footer1" :price="(totalPrice*100)" button-text="提交订单" @submit="onSubmit">
        <!-- 全选按钮 -->
        <van-radio :checked="selectAll" class="select-item" name="1" @click="updateAllFn(user_id , !selectAll)">全选</van-radio>
       
   
    </van-submit-bar>
    <footer class="footer2"></footer>
</template>

<script setup lang="ts">
import router from '@/router';
import footer from '@/views/Footer/footer.vue'
import { Dialog, Toast } from 'vant';
import { ref, onMounted, computed } from 'vue';
import { useRouter, type Router } from 'vue-router'
import { cartlistApi, updateApi,updateAllApi, cartremoveApi } from '@/api/cart'
import type { MyMiaoSaItem } from '@/config/interface'
import { recommendlistApi } from '@/api/goods'
import { addOrderApi} from '@/api/order'
const $router: Router = useRouter()
const token = window.localStorage.getItem('token')
const user_id = window.localStorage.getItem('user_id')
//返回上一页
const tobackFn = () => {
    router.go(-1)
}



//上来先验证token和id
const testToken = () => {

    if (!token || !user_id) {
        Dialog({
            title: '提示',
            message: '您还没有登录',         
        }).then(() => {
           
        })
    }
}

//获取购物车列表
const cartList = ref<MyMiaoSaItem[]>([])
const getCartList = async () => {
    const res = await cartlistApi(user_id as string)
    console.log('购物车列表', res);
    cartList.value = res.data
}

//获取热门搜索
const recommendlist = ref<MyMiaoSaItem[]>([])

const HotwordList = async () => {
    const res = await recommendlistApi()
    console.log(123, res);
    recommendlist.value = res.data
}

onMounted(
    () => {
        testToken(),
            getCartList()
        HotwordList()      
    }
)
//删除功能
const delFn = async (cartid: string) => {
    console.log('删除');
    const res = await cartremoveApi(cartid)
    console.log(res);
    if (res.code == '200') {
        Dialog({
            title: '提示',
            message: '删除成功'
        })

    }
    getCartList()
}

//准备一个全选
const selectAll = computed(() => {
    return cartList.value.every(item => item.flag)
   
})

//全选控制单选-----------------------------
const updateAllFn = async(user_id:string , selectAll:boolean)=>{
    const res = await updateAllApi(user_id,selectAll)
    console.log(123123 , selectAll);
    if (res.code === '200') {
    getCartList()
  }
}


//修改购物车的单个选中状态
const updateStatus = async (id: string, flag: boolean) => {
    const res = await updateApi(id, flag)
    console.log(111111 , res);
    if (res.code === '200') {
    getCartList()
  }
}

//价格计算
const totalPrice = computed(() => {
  return cartList.value.reduce((prev, item) => {
    if (item.flag) {
      return prev + (item.originprice * item.num)
    } else {
      return prev
    }
  }, 0)
})


//生成订单
const addOrderheader =async ()=>{
    const res = await addOrderApi(user_id as string)
    console.log(res);  
      //把订单信息存储在浏览器内  注意这个断言的书写*************
    window.localStorage.setItem('time' ,((res as unknown) as {time:string}) .time)
}

//提交订单
const onSubmit = () => {
    addOrderheader()
     $router.push({path: '/order' })
};




</script>
<style scoped lang="scss">
.box {
    display: flex;
    padding: 0 15px;
    overflow: hidden;
    margin-bottom: 15px;
    background-color: white;
}

.imgbox {
    width: 100px;
    height: 100px;
    display: flex;
    align-items: center;

    img {
        width: 100px;
        height: 100px;
        display: block;
    }

    .checkboxAll {
        border: 1px solid black;
        margin-right: 5px;
        border-radius: 50%;
    }
}

.rightBox {
    margin-left: 40px;
}

.pronamebox {
    width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.footer1 {
    position: fixed;
    bottom: 50px;
}

.van-submit-bar__tip {
    margin-top: 50px;
}

.footer2 {
    margin-top: 120px;
}

.recommend {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0 15px;
    box-sizing: border-box;

    >li {
        width: 48%;
        margin-bottom: 10px;

        img {
            width: 100%;
        }
    }
}
</style>